<template>
  <div>
    <!-- 面包屑 -->
    <breadcrumb
      :breadcrumbArr="jsList.breadcrumbArr"
      :breadcrumbLastItem="breadcrumbLastItem"
      :state="state"
      @handleBack="handleBack"
    />
    <div v-if="isTrue" class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-tabs
          v-model="activeName"
          class="el-tabs__customize"
          @tab-click="handleTabsClick"
        >
          <el-tab-pane label="基本信息" name="first">
            <baseInfo ref="baseInfo" :detail="detailInfo" />
          </el-tab-pane>

          <el-tab-pane label="财务信息" name="second">
            <financeInfo
              ref="financeInfo"
              :detail="detailInfo"
              :isShow="isShow"
            />
          </el-tab-pane>

          <el-tab-pane label="采购清单" name="third">
            <purchaseList
              ref="purchaseList"
              :isShow="isShow"
              :detail="detailInfo"
            />
          </el-tab-pane>

          <el-tab-pane label="使用范围" name="fourth">
            <useRange ref="useRange" :detail="detailInfo" />
          </el-tab-pane>

          <el-tab-pane label="付款方式" name="fifth">
            <paymentMode ref="paymentMode" :detail="detailInfo" />
          </el-tab-pane>

          <el-tab-pane label="合同附件" name="sixth">
            <contractAppendix ref="contractAppendix" isTab v-model="uploadList">
              <div slot="tooltip">
                <el-alert
                  title="请上传起草合同文件"
                  type="error"
                  :closable="false"
                />
              </div>
            </contractAppendix>
          </el-tab-pane>

          <el-tab-pane v-if="state === 'edit'" label="变更历史" name="seventh">
            <oneLineTable
              ref="histryChanges"
              :highlightNodeArr="['contractCode']"
              :tableTheadOptions="jsList.histryChangeTableThead"
              :oneLineTableData="detailInfo.oldSmpPcConcList"
              @gotoDetail="gotoDetail"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--  按钮  -->
    <el-bottom-guide>
      <ul class="ccui-bottom-button">
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle(2)"
            >暂存
          </el-button>
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle(0)"
            >保存并校验
          </el-button>
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle(1)"
            >保存并提交
          </el-button>
        </li>
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
            >返回
          </el-button>
        </li>
      </ul>
    </el-bottom-guide>

    <exportQr v-if="state === 'edit'" type="login" />
  </div>
</template>

<script>
import jsList from "../js";
import baseInfo from "./baseInfo";
import contractComponent from "@/app/contractManagement/components";
import purchaseList from "./purchaseList";
import publicComponent from "@/basa/components/public";
import Mixin from "../mixins";
import {
  saveSmpContractCreation,
  editSmpContractCreation,
  getSmpPcConc
} from "../api";
import { mapActions, mapGetters } from "vuex";
import { proxyDateFormat } from "@/basa/utils";

export default {
  mixins: [Mixin],
  props: {
    state: {
      type: String,
      default: ""
    }
  },
  components: {
    baseInfo,
    financeInfo: contractComponent.financeInfo,
    purchaseList,
    useRange: contractComponent.useRange,
    paymentMode: contractComponent.paymentMode,
    contractAppendix: publicComponent.uploadInfo,
    breadcrumb: publicComponent.breadcrumb,
    oneLineTable: publicComponent.oneLineTable,
    exportQr: publicComponent.exportQr
  },
  data() {
    return {
      breadcrumbLastItem: "合同起草",
      activeName: "first",
      isTrue: false,
      isShow: false,
      detailInfo: {},
      isFocus: "baseInfo",
      uploadList: [],
      tabsSelectArr: [],
      taxRateObj: {},
      afterVal: ""
    };
  },
  // created() {
  //   this.init();
  // },
  activated() {
    this.init();
  },
  deactivated() {
    this.nextIsTrue();
  },
  methods: {
    init() {
      if (this.state === "edit") {
        this.getSmpPcConcInfo();
      } else {
        this.detailInfo = Object.assign({}, { state: this.state });
        this.isTrue = true;
      }
    },

    handleTabsClick({ label, name }) {
      if (["second", "third"].includes(name)) {
        this.isShow = true;
      } else {
        this.isShow = false;
      }
    },

    // 保存 提交
    async submitHandle(operType) {
      try {
        let smpPcConcBO,
          smpProjectReqBO,
          pcFinanceBOS,
          smpConcMatLessListBOList,
          smpUsableRangeBOList,
          payTypeListBOS;

        const { baseInfo, financeInfo, purchaseList, useRange, paymentMode } =
          this.$refs;

        if (operType == 2) {
          // 暂存
          // 基础合同
          smpPcConcBO = purchaseList.purchaseList.length
            ? await baseInfo.beforeSubmitTemp()
            : baseInfo.form;
          // 财务信息
          pcFinanceBOS = financeInfo.cardData;
          // 采购清单
          smpConcMatLessListBOList = await purchaseList.beforeSubmitTemp();
          // 使用范围
          smpUsableRangeBOList = useRange.useRangeList;
          // 付款方式
          payTypeListBOS = await paymentMode.beforeSubmitTemp();
          // 项目名称
          if (baseInfo.form.projectCode) {
            smpProjectReqBO = baseInfo.smpProjectReqBO;
          } else {
            smpProjectReqBO = {};
          }
        } else {
          // 基础合同
          smpPcConcBO = await baseInfo.handleSubmit();
          // 财务信息
          pcFinanceBOS = await financeInfo.handleSubmit();
          // 采购清单
          smpConcMatLessListBOList = await purchaseList.handleSubmit();
          // 使用范围
          smpUsableRangeBOList = await useRange.handleSubmit();
          // 付款方式
          payTypeListBOS = await paymentMode.handleSubmit();
          // 项目名称
          smpProjectReqBO = baseInfo.smpProjectReqBO;
        }

        // 附件上传
        const fileReqBOS = this.uploadList.map((n, i) => ({
          sn: i,
          createTime: n.createTime,
          fileDesc: n.fileDesc,
          fileInfoId: n.uploadId || n.fileInfoId
        }));

        if (pcFinanceBOS.length) {
          pcFinanceBOS.forEach(item => {
            item.materialSource = smpPcConcBO.materialSource;
            item.materialSourceCode = smpPcConcBO.materialSourceCode;
            item.contractPerson = smpPcConcBO.contractPerson;
            item.contractPersonTel = smpPcConcBO.contractPersonTel;
          });
        }

        let thirdCategoriesOfName = "";

        if (smpConcMatLessListBOList && smpConcMatLessListBOList.length) {
          thirdCategoriesOfName =
            smpConcMatLessListBOList[0].thirdCategoriesOfName;

          if (this.taxRateObj.dicValue !== "免税") {
            const newVal = this.taxRateObj.dicValue
              ? this.taxRateObj.dicValue.match(/\d+(.\d+)?/g)[0]
              : 0;
            this.afterVal = Number(newVal) / 100;
          } else {
            this.afterVal = this.taxRateObj.dicKey;
          }

          if (!this.getMultiRateCode) {
            smpConcMatLessListBOList = smpConcMatLessListBOList.map((n, i) => ({
              ...n,
              taxRateCode: this.taxRateObj.dicKey,
              taxRatePercent: this.taxRateObj.dicValue,
              taxRate: this.afterVal
            }));
          }

          smpConcMatLessListBOList.map((n, i) => {
            n.sn = i;
          });
        }

        if (smpPcConcBO) {
          smpPcConcBO = {
            ...smpPcConcBO,
            thirdCategoriesOfName
          };
        }

        if (payTypeListBOS.length) {
          payTypeListBOS = payTypeListBOS.map((n, i) => ({
            smpPayTypeBO: {
              ...n.smpPayTypeBO,
              sn: i,
              id: this.state === "create" ? null : n.smpPayTypeBO.id
            },
            smpPayTypeItemBOS: n.smpPayTypeItemBOS.map((m, i) => ({
              ...m,
              sn: i,
              id: this.state === "create" ? null : m.id
            }))
          }));
        }

        if (smpUsableRangeBOList.length) {
          smpUsableRangeBOList.map((n, i) => {
            n.sn = i;
          });
        }

        const data = {
          smpPcConcBO,
          pcFinanceBOS,
          smpConcMatLessListBOList,
          smpUsableRangeBOList,
          payTypeListBOS,
          fileReqBOS, // 合同附件
          smpProjectReqBO, // 项目信息
          operType
        };

        (this.state === "create"
          ? saveSmpContractCreation
          : editSmpContractCreation)(data).then(res => {
          const { code, message } = res.data;
          if (code === "0") {
            this.$message.success(message);
            this.handleBack();
          }
        });
      } catch (error) {
        this.activeName = error;
        if (["first", "second"].includes(error)) {
          this.$nextTick(() => {
            const errorFormEl = document.body.querySelector(".is-error");
            const errorText = errorFormEl.firstChild.innerText;
            const messageText = errorText.substring(
              0,
              errorText.lastIndexOf("：")
            );
            this.$showErrorMessage(`${messageText}未填写，请编辑后保存`);
            if (errorFormEl) {
              errorFormEl.scrollIntoView({
                behavior: "smooth", // 平滑过渡
                block: "start" // 上边框与视窗顶部平齐。默认值
              });
            }
          });
        }
      }
    },

    // 获取详情
    getSmpPcConcInfo() {
      const { id } = this.$route.params;
      const data = { concId: id, isShowWorkflow: 1 };
      getSmpPcConc(data)
        .then(res => {
          const {
            data: { data }
          } = res;

          this.setTaxRateObj({
            dicKey: data.smpPcConc.taxRateCode,
            dicValue: data.smpPcConc.taxRatePercent
          });
          this.setCurrencyObj({
            code: data.smpPcConc.currencyCode,
            name: data.smpPcConc.currencyName
          });
          this.setOrgId(data.smpPcConc.reportInOrgId);
          this.setTaxRate(data.smpPcConc.taxRate / 100);
          this.setMultiRateCode(data.smpPcConc.multiRateCode === 0);
          this.setShowDoubleTable(!!data.smpPcConc.partyBId);
          this.setSupplierData({ supplierCode: data.smpPcConc.partyBId });
          this.setAgreementSelectStatus(!!data.smpPcConc.protocalCode);
          this.setIsOverseas(data.smpPcConc.isOverseas);

          // 处理变更历史
          if (data.oldSmpPcConcList.length) {
            data.oldSmpPcConcList = data.oldSmpPcConcList.map(n => ({
              ...n,
              compileDateStr: n.compileDate
                ? proxyDateFormat(n.compileDate)
                : ""
            }));
          }

          this.detailInfo = Object.assign(data, {
            state: this.state
          });

          // 过滤附件
          this.uploadList = data.concFiles.filter(_ =>
            ["1", "2", "3"].includes(_.businessSonType)
          );

          this.breadcrumbLastItem = data.smpPcConc.contractName;
          this.isTrue = true;
        })
        .catch(e => {});
    },

    gotoDetail({ id }) {
      this.$router.push(
        `/contractManagement/equipmentContractDraft/item-detail/${id}`
      );
    },

    ...mapActions([
      "setTaxRate",
      "setTaxRateObj",
      "setOrgId",
      "setMultiRateCode",
      "setShowDoubleTable",
      "setSupplierData",
      "setAgreementSelectStatus",
      "setEchoProtocalData",
      "setIsOverseas",
      "setCurrencyObj"
    ])
  },
  computed: {
    ...mapGetters([
      "getTaxRateObj",
      "getMultiRateCode",
      "getSpecificationsArr" // 物资编码规则
    ]),
    jsList: () => jsList
  },
  watch: {
    getTaxRateObj(newVal) {
      this.taxRateObj = newVal;
    }
  }
};
</script>

<style lang="scss" scoped>
.el-tabs__customize {
  padding-bottom: 50px;
}
</style>
